function getToken() {
  const token = wx.getStorageSync('user_token');
  return token;
}

function getRefreshToken() {
  const refreshToken = wx.getStorageSync('user_refreshToken');
  return refreshToken;
}

function refreshToken() {
  const refreshToken = getRefreshToken();
  if (!refreshToken) {
    return Promise.reject('没有可用的刷新令牌');
  }

  const refreshUrl = baseURL + '/api/travelGraphy/auth/wxRefreshToken';
  const data = {
    refreshToken: refreshToken
  };

  return new Promise((resolve, reject) => {
    const token = getToken();
    wx.request({
      url: refreshUrl,
      data: wx.getStorageSync('user_refreshToken'),
      method: 'GET',
      timeout: 5000,
      success: (result) => {
        if (result.data && result.data.code === 200) {
          const newToken = result.data.token;
          wx.setStorageSync('user_token', newToken);
          resolve(newToken);
        } else {
          reject('刷新令牌失败');
        }
      },
      fail: (err) => {
        reject('请求刷新令牌失败: ' + err.message);
      }
    });
  });
}


//const baseURL = 'https://travel.peibanmao.com'
const baseURL = 'http://192.168.0.9:8089'
const request = (options) => {
  const token = getToken();
  return new Promise(function (resolve, reject) {
    let header = {
      'content-type': "application/json",
    }
    if (token) {
      header['Authorization'] = `Bearer ${token}`;
    }
    wx.request({
      url: baseURL + options.url,
      data: options.data,
      header: options.header,
      method: options.method,
      timeout: 5000,
      success: (result) => {
        if (result.data && result.data.code === 200) {
          resolve(result.data);
        } else if (result.data && result.data.code === 500) {
          refreshToken().then((newToken) => {
            // 更新options的headers，使用新令牌重新发起请求  
            options.headers = {
              ...options.headers,
              'Authorization': `Bearer ${newToken}`
            };
            // 递归调用request函数  
            request(options).then(resolve).catch(reject);
          }).catch((refreshError) => {
            reject('刷新令牌失败: ' + refreshError);
          });
        } else {
          console.log('reject', result, 's')
          reject(result.data.msg || '请求错误');
        }
      },
      fail: (err) => {
        // 请求失败的回调  
        reject(err.message || '请求失败');
      }
    });
  })
}
export default request